from database import sqlUtils
from mapper.pojo import StockMarket, StockUpdateRecord

import tushare as ts


def update_day_stock_by_code(queue):
    count = 0
    while not queue.empty():
        try:
            session = sqlUtils.get_sqlalchemy_session()
            ts_code = queue.get()
            df = ts.pro_bar(ts_code=str(ts_code), adj='qfq', ma=[5, 10, 20, 30, 60, 120, 250],
                            factors=['vr', 'tor'])
            print("代码为" + ts_code + "正在插入数据")
            if df is not None:
                d_len = df.shape[0]
                update_market_date = None
                for index in range(d_len):
                    resu1 = df.iloc[index]
                    if index == 0:
                        update_market_date = str(resu1.trade_date)
                    stock_market = StockMarket.tranfer(resu1)
                    session.merge(stock_market)
                session.commit()
                print("代码为" + ts_code + "插入数据完成")
                if update_market_date is not None:
                    # 更新当前代码的最新更新日期
                    stock_update_record = StockUpdateRecord(ts_code=ts_code, update_market_date=update_market_date)
                    session.merge(stock_update_record)
                    session.commit()
                count = count + 1
                session.close()
        except Exception:
            print("代码为" + ts_code + "插入数据失败")
    print("当前进程完成插入的数目是{}".format(count))
    return count
